import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

public class Parser
{
	Download d;
	String content;
	Vector<RNASet> rnaset;
	RNASet seukarya;
	RNASet sarchaea;
	RNASet sbacteria;
	String setname;
	String familyname;
	String speciesname;
	int eukarya, archaea, bacteria;
	BufferedWriter output;
	BufferedWriter outputEukarya;
	BufferedWriter outputBacteria;
	BufferedWriter outputArchaea;
	String file;
	String rsselement;

	public Parser(Download ws)
	{
		d = ws;
		rnaset = new Vector<RNASet>();
		seukarya = new RNASet("Eukarya");
		sarchaea = new RNASet("Archaea");
		sbacteria = new RNASet("Bacteria");
		content = "";
		setname = "";
		familyname = "";
		speciesname = "";
		eukarya = 0;
		archaea = 0;
		bacteria = 0;
		rsselement = "";
	}

	public Vector<RNASet> getRnaset()
	{
		return rnaset;
	}

	/*
	 * Function which get the page content back
	 */
	public void getContent(int euk, int arch, int bact) throws IOException
	{
		String line = "";
		String href = "";
		int start, end = 0;
		while ((line = d.getSource().readLine()) != null)
		{
			// We get href to create a link for secondary structures
			if (line.contains("<td align=left width=33.3%><a href="))
			{
				start = line.indexOf("href");
				end = line.indexOf("/\">");
				System.out.println("LINE: \n" + line);
				href = line.substring(start + 6, end);

				start = end;
				end = line.indexOf("</a>");
				speciesname = line.substring(start + 3, end);

				if ((setname.equals("Eukarya") && (euk == 1))
						|| (setname.equals("Archaea") && (arch == 1))
						|| (setname.equals("Bacteria") && (bact == 1)))
				{
					searchSS(href, setname, familyname, speciesname);
				}

				// We get the set name (Eucharya, ...)
			} else if (line.contains("table_header1"))
			{
				start = line.indexOf("</a>");
				end = line.indexOf("</td>");
				setname = line.substring(start + 4, end);
				rnaset.add(new RNASet(setname));
				// We get the species name
			} else if (line.contains("table_header2"))
			{
				start = line.indexOf("<b>");
				end = line.indexOf("</b>");
				familyname = line.substring(start + 3, end);
			}
		}

		if (euk == 1)
		{
			rnaset.add(seukarya);
			writeContent("Eukarya");
		}
		if (arch == 1)
		{
			rnaset.add(sarchaea);
			writeContent("Archaea");

		}
		if (bact == 1)
		{
			rnaset.add(sbacteria);
			writeContent("Bacteria");
		}

		closeFile();

	}

	public void closeFile()
	{
		try
		{
			// output.close();
			outputEukarya.close();
			outputBacteria.close();
			outputArchaea.close();
		} catch (Exception e)
		{
		}
	}

	public void openFile(String setname, String filename)
	{
		try
		{
			String fileaddress = System.getProperty("user.dir")
					+ File.separator + filename;
			File f = new File(fileaddress);
			if (f.exists())
			{
				f.delete();
			}
			FileWriter fw = new FileWriter(fileaddress, true);

			if (setname.equals("Eukarya"))
			{

				outputEukarya = new BufferedWriter(fw);
				// setFirstLine(outputEukarya);
			} else if (setname.equals("Archaea"))
			{

				outputArchaea = new BufferedWriter(fw);
				// setFirstLine(outputArchaea);
			} else if (setname.equals("Bacteria"))
			{

				outputBacteria = new BufferedWriter(fw);
				// setFirstLine(outputBacteria);
			}

		} catch (Exception e)
		{
		}
	}

	public void setFirstLine(BufferedWriter bw)
	{
		try
		{
			bw.write("Famille;Espece;name;longueur;type;Anticodon;Position;Score;Seq;Str");
			bw.newLine();
		} catch (Exception e)
		{
		}

	}

	public void searchSS(String href, String sename, String fname, String spname)
			throws IOException
	{
		String ssline = "";
		String sscontent = "";
		int readpre = 0;
		String sslink = "http://gtrnadb.ucsc.edu/" + href + "/" + href
				+ "-structs.html";
		System.out.println(sslink);
		CONSTANT.writeConsole(sslink);
		Download sspage = new Download(sslink);
		while ((ssline = sspage.getSource().readLine()) != null)
		{
			// Begin of usefull information
			if (ssline.contains("<PRE>"))
			{
				readpre = 1;
				sscontent += ssline;
				ssline = "";
			}
			// End of usefull information
			if (ssline.contains("</PRE>"))
			{
				readpre = 0;
				sscontent += ssline;
				if (sscontent.length() > 12)
				{
					parseSS(sscontent, sename, fname, spname);
				}

				sscontent = "";
			}
			// Content in <PRE>...</PRE>
			if (readpre == 1)
			{
				sscontent += ssline;
			}
		}
	}

	public void parseSS(String ss, String sename, String fname, String spname)
			throws IOException
	{
		String ssname, sstype, ssanticodon, ssseq, ssstruct = "";
		int start, end, sslength, ssanticodonpos = 0;
		float ssscore = 0;
		// name
		start = 5;
		end = ss.indexOf("(");
		ssname = ss.substring(start, end);
		// length
		start = ss.indexOf("Length:");
		end = ss.indexOf("bp");
		sslength = Integer.parseInt(ss.substring(start + 8, end - 1));
		// type
		start = ss.indexOf("Type:");
		sstype = ss.substring(start + 6, start + 9);
		// anticodon
		start = ss.indexOf("Anticodon:");
		end = ss.indexOf(" at ");
		ssanticodon = ss.substring(start + 11, end);
		// position anticodon
		start = ss.indexOf(" at ");
		// start = end;
		end = ss.indexOf("-", start);
		ssanticodonpos = Integer.parseInt(ss.substring(start + 4, end));
		// score
		start = ss.indexOf("Score:");
		end = ss.indexOf("Seq:");
		ssscore = Float.parseFloat(ss.substring(start + 7, start + 12));
		// sequence
		start = ss.indexOf("Seq:");
		end = ss.indexOf("Str:");
		if (end >= start + 5)
		{
			ssseq = ss.substring(start + 5, end);
			// structure
			start = ss.indexOf("Str:");
			end = ss.indexOf("</PRE>");
			ssstruct = ss.substring(start + 5, end);
		} else
		{
			ssseq = new String();
			ssstruct = new String();
		}

		RNASecondaryStructure rss = null;
		rss = new RNASecondaryStructure(ssname, sslength, sstype, ssanticodon,
				ssanticodonpos, ssscore, ssseq, ssstruct);
		for (int i = 0; i < rnaset.size(); i++)
		{
			if (rnaset.elementAt(i).getName().equals(sename))
			{
				if (sename.equals("Eukarya"))
				{
					eukarya++;
					seukarya.addToFamily(fname, spname, rss);
				} else if (sename.equals("Archaea"))
				{
					archaea++;
					sarchaea.addToFamily(fname, spname, rss);
				} else if (sename.equals("Bacteria"))
				{
					bacteria++;
					sbacteria.addToFamily(fname, spname, rss);
				}
			}
		}
	}

	public void writeContent(String sename)
	{
		// Try catch exception
		try
		{
			if (sename.equals("Eukarya"))
			{
				seukarya.writeData(outputEukarya);
				outputEukarya.close();
			} else if (sename.equals("Archaea"))
			{
				sarchaea.writeData(outputArchaea);
				outputArchaea.close();
			} else if (sename.equals("Bacteria"))
			{
				sbacteria.writeData(outputBacteria);
				outputBacteria.close();
			}
		} catch (IOException ioe)
		{
			System.out.print("Error : ");
			ioe.printStackTrace();
		}
	}

	public class DownloadContent extends Thread implements Runnable
	{
		String href, setname, familyname, speciesname;

		public DownloadContent(String href, String setname, String familyname,
				String speciesname)
		{
			this.href = href;
			this.setname = setname;
			this.familyname = familyname;
			this.speciesname = speciesname;
		}

		public void run()
		{
			try
			{
				searchSS(href, setname, familyname, speciesname);
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	class DownloadThread extends Thread implements Runnable
	{
		public DownloadThread()
		{
			super();
		}

		public void run()
		{
			System.out.println("Lancement du thread");
		}
	}
}
